#!/bin/bash

#------------------------------------------------------------------------------
# Searches a directory passed as the first argument for any files containing the
# M4 'include' macro call, then, if called with the '-d' flag, outputs a parsed
# a dictionary in the format:
#
# file1:dependencies
# file2:dependencies
# file3:dependencies
#
# Or outputs only the files without any dependencies.
#
# Both of these outputs should then be parsed by Make to generate dynamic
# recipes.
#------------------------------------------------------------------------------

# TODO: Implement proper argument handling
print_with_deps_only=0
[[ "$1" == '-d' ]] && print_with_deps_only=1 && shift

postdir="$1"
key=''
declare -A posts_to_deps
posts_with_deps="$(\
	grep 'include\(.*\)' -r $postdir | \
	sed -E -e 's/include\(//' -e 's/\)//' \
)"

# Get posts with dependencies
for toparse in $posts_with_deps; do 
	IFS=:
	for entry in $toparse ; do
		if [[ "$entry" == *post.* ]] ; then
			[[ "$entry" == "$key" ]] && continue
			key=$entry
		else 
			[[ -n ${posts_to_deps["$key"]} ]] && entry=":$entry"
			posts_to_deps["$key"]+="$entry"
		fi
	done
	unset IFS
done

posts=''
for post in "${!posts_to_deps[@]}" ; do
	((print_with_deps_only)) && echo "$post:${posts_to_deps[$post]}"
	posts+="$post\n"
done

if ! ((print_with_deps_only)) ; then
	all_posts=$(find . -wholename './parts' -prune -o -name '*.post.html' -print)
	sort <<< $(printf "$all_posts\n$posts") | uniq -u
fi
